package teleradiologia.repository;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateTemplate;

import teleradiologia.domain.Radiologylab;
import teleradiologia.utils.HibernateUtil;

public class RadiologylabDaoImpl implements RadiologylabDao {

	@Override
	public String create(Radiologylab radiologylab) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		String krsnumber = (String)session.save(radiologylab);

		tx.commit();
		session.close();
		
		return krsnumber;
	}

	@Override
	public void delete(Radiologylab radiologylab) {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.delete(radiologylab);

		tx.commit();
		session.close();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Radiologylab> getAll() {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		List<Radiologylab> radiologylabs = session
				.createQuery(
						"from Radiologylab radiologylab order by radiologylab.name asc")
				.list();

		tx.commit();
		session.close();
		
		return radiologylabs;
	}

	@Override
	public Radiologylab getByKrsnumber(String krsnumber) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Radiologylab radiologylab = (Radiologylab) session.get(
				Radiologylab.class, krsnumber);

		tx.commit();
		session.close();

		return radiologylab;
	}

	@Override
	public void update(Radiologylab radiologylab) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.update(radiologylab);

		tx.commit();
		session.close();
	}

	@Override
	public void deleteAll() {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		Query q = session.createQuery("delete from Radiologylab"); 
		q.executeUpdate();
		
		tx.commit();
		session.close();
	}
}
